<template>
  <el-dialog v-model="visible" :close-on-click-modal="false" width="821" custom-class="login-dialog" @open="handleOpen">
    <template #default>
      <div class="login-dialog-content">
        <!-- 左侧扫码登录区域 -->
        <!-- <div class="scan-login-section">
        <div class="sub-scan-login-section">
          <div id="wechat_qrlogin"></div>
          <div class="scan-qr-code">
            <img class="qr-code-img" src="../assets/images/login/login-qrcode.png" alt="">
          </div>
          <div class="scan-login-text">
            <img class="text-img" src="../assets/images/login/wx-logo.png" alt="">
            微信扫码登录
          </div>
        </div>
      </div> -->

        <!-- 右侧账号登录区域 -->
        <div class="account-login-section">
          <div class="sub-account-login-section">
            <div class="login-tabs">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="验证码登录" name="sms"></el-tab-pane>
                <el-tab-pane label="密码登录" name="password"></el-tab-pane>
              </el-tabs>
            </div>

            <!-- 验证码登录表单 -->
            <el-form ref="smsFormRef" :model="smsForm" :rules="smsRules" v-if="activeTab === 'sms'" class="login-form">
              <el-form-item prop="phone" :validate-event="false">
                <el-input v-model="smsForm.phone" placeholder="请输入手机号" @input="handlePhoneInput($event, 'sms')"
                  clearable></el-input>
              </el-form-item>
              <el-form-item prop="smsCode" :validate-event="false">
                <el-input v-model="smsForm.smsCode" placeholder="请输入验证码" class="sms-code-input" clearable>
                  <template #append>
                    <el-button type="text" :disabled="smsButtonDisabled" @click="handleGetSmsCode"
                      class="get-sms-button">
                      {{ smsButtonText }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :class="smsLoginButtonClass" @click="handleSmsLogin" :loading="loading">
                  登录
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 密码登录表单 -->
            <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" v-else class="login-form">
              <el-form-item prop="phone" :validate-event="false">
                <el-input v-model="passwordForm.phone" placeholder="请输入手机/用户名" clearable></el-input>
                <!-- @input="handlePhoneInput($event, 'password')"  -->
              </el-form-item>
              <el-form-item prop="password" :validate-event="false">
                <el-input v-model="passwordForm.password" :type="showPassword ? 'text' : 'password'"
                  placeholder="请输入密码">
                  <template #suffix>
                    <div class="password-toggle-icon" @click="togglePasswordVisibility">
                      <View v-if="showPassword" />
                      <Hide v-else />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="form-actions">
                <div class="left-actions">
                  <el-checkbox v-model="passwordForm.rememberMe" class="remember-me">记住密码</el-checkbox>
                </div>
                <div class="right-actions">
                  <el-checkbox v-model="passwordForm.autoLogin" class="remember-me auto-login">自动登录</el-checkbox>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :class="passwordLoginButtonClass" @click="handlePasswordLogin"
                  :loading="loading">
                  登录
                </el-button>
              </el-form-item>
              <el-link type="primary" class="forgot-password" :underline="false"
                @click="handleForgotPassword">忘记密码？</el-link>
            </el-form>

            <!-- 用户协议 -->
            <div class="agreement-section">
              <el-checkbox v-model="agreementChecked" class="agreement-checkbox">
                我已阅读并同意
                <el-link type="primary" :underline="false" @click="handleAgreementClick('user')">《用户协议》</el-link>
                <el-link type="primary" :underline="false" @click="handleAgreementClick('privacy')">《隐私政策》</el-link>
                <el-link type="primary" :underline="false" @click="handleAgreementClick('platform')">《平台免责声明》</el-link>
              </el-checkbox>
            </div>
          </div>
        </div>
      </div>

      <!-- 校验手机号弹窗 -->
      <VerifyPhone append-to-body v-model="innerVisible" ref="VerifyPhoneDialogRef" @backLogin="handleBackLogin" />
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { Hide, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import errorIcon from '@/assets/images/error-icon.png'
import { useUserStore } from '../stores/user'
import { useRouter } from 'vue-router'
import { domesticUserCenter } from 'ld-web-sdk';
import VerifyPhone from '@/components/VerifyPhone.vue'
// import CryptoJS from 'crypto-js';

// 定义组件名称
defineOptions({
  name: 'LoginDialog'
})

// 定义事件
const emit = defineEmits(['loginSuccess'])

// 状态管理
const userStore = useUserStore()
const router = useRouter()

// 弹窗显示状态
const visible = ref(false)
const innerVisible = ref(false)

// 登录方式切换
const activeTab = ref('sms')

// 表单引用
const smsFormRef = ref(null)
const passwordFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 密码可见性
const showPassword = ref(false)

// 切换密码可见性
const togglePasswordVisibility = (event) => {
  showPassword.value = !showPassword.value
  // 阻止事件冒泡，避免触发输入框的失焦事件
  event.stopPropagation()
}

// 协议同意
const agreementChecked = ref(false)

// 验证码按钮状态
const smsButtonDisabled = ref(false)
const smsButtonText = ref('获取验证码')
let smsCountdown = null

// 表单验证状态
const smsFormValid = ref(false)
const passwordFormValid = ref(false)

// 验证码登录表单数据
const smsForm = reactive({
  phone: '',
  smsCode: ''
})

// 密码登录表单数据
const passwordForm = reactive({
  phone: '',
  password: '',
  rememberMe: false,
  autoLogin: false
})


// 提取正则表达式为常量
const REGEX_PHONE = /^1[3-9]\d{9}$/
const REGEX_USERNAME = /^[a-zA-Z0-9_]{4,20}$/
const REGEX_SMS_CODE = /^\d{4,6}$/

// 验证手机号格式
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!REGEX_PHONE.test(value) && !REGEX_USERNAME.test(value)) {
    callback(new Error('手机号格式不正确'))
  } else {
    callback()
  }
}

// 验证验证码格式
const validateSmsCode = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else if (!REGEX_SMS_CODE.test(value)) {
    callback(new Error('验证码格式不正确'))
  } else {
    callback()
  }
}

// 验证密码格式
const validatePassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 8 || value.length > 16) {
    callback(new Error('密码长度在8-16位之间'))
  } else {
    callback()
  }
}

// 验证码登录表单验证规则
const smsRules = {
  phone: [
    {
      required: true,
      validator: validatePhone,
      trigger: ['blur', 'input']
    }
  ],
  smsCode: [
    {
      required: true,
      validator: validateSmsCode,
      trigger: ['blur', 'input']
    }
  ]
}

// 密码登录表单验证规则
const passwordRules = {
  phone: [
    {
      required: true,
      message: '请输入手机号/用户名',
      trigger: ['blur', 'input']
    }
  ],
  password: [
    {
      required: true,
      validator: validatePassword,
      trigger: ['blur', 'input']
    }
  ]
}

// 清理表单数据
const clearFormData = () => {
  // 重置表单实例
  if (smsFormRef.value) {
    smsFormRef.value.resetFields()
  }
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }

  // 清空表单字段值
  smsForm.phone = ''
  smsForm.smsCode = ''
  passwordForm.phone = ''
  passwordForm.password = ''

  // 重置验证状态
  smsFormValid.value = false
  passwordFormValid.value = false
  agreementChecked.value = false // 默认不勾选协议，符合大多数用户习惯

  // 重置loading状态
  loading.value = false
}

const handleBackLogin = (userData) => {
  innerVisible.value = false
}

// 监听表单输入变化，实时验证 - 合并后的watch监听器
watch([
  () => smsForm.phone,
  () => smsForm.smsCode,
  () => passwordForm.phone,
  () => passwordForm.password,
  agreementChecked,
  visible
], ([newSmsPhone, newSmsCode, newPwdPhone, newPassword, newAgreement, newVisible], [oldSmsPhone, oldSmsCode, oldPwdPhone, oldPassword, oldAgreement, oldVisible]) => {
  // 处理表单输入变化的验证
  if (newSmsPhone !== oldSmsPhone || newSmsCode !== oldSmsCode) {
    validateSmsForm()
  }
  if (newPwdPhone !== oldPwdPhone || newPassword !== oldPassword) {
    validatePasswordForm()
  }

  // 处理协议勾选状态变化
  if (newAgreement !== oldAgreement) {
    validateSmsForm()
    validatePasswordForm()
  }

  // 处理弹窗关闭时清理表单
  if (oldVisible === true && newVisible === false) {
    clearFormData()
  }
})

// 验证验证码表单
const validateSmsForm = () => {
  if (!smsFormRef.value) return

  const phoneValid = REGEX_PHONE.test(smsForm.phone) || REGEX_USERNAME.test(smsForm.phone)
  const codeValid = REGEX_SMS_CODE.test(smsForm.smsCode)
  smsFormValid.value = phoneValid && codeValid && agreementChecked.value
}

// 验证密码表单
const validatePasswordForm = () => {
  if (!passwordFormRef.value) return

  const phoneValid = REGEX_PHONE.test(passwordForm.phone) || REGEX_USERNAME.test(passwordForm.phone)
  const passwordValid = passwordForm.password.length >= 6 && passwordForm.password.length <= 20
  passwordFormValid.value = phoneValid && passwordValid && agreementChecked.value
}

// 监听协议勾选状态变化已合并到上面的复合watch中

// 登录按钮样式类
const smsLoginButtonClass = computed(() => ({
  'login-submit-button': true,
  'login-submit-button-active': smsFormValid.value
}))

const passwordLoginButtonClass = computed(() => ({
  'login-submit-button': true,
  'login-submit-button-active': passwordFormValid.value
}))

// 显示登录弹窗
const showLoginDialog = () => {
  visible.value = true
}

// 隐藏登录弹窗
const hideLoginDialog = () => {
  visible.value = false
  // 清除验证码倒计时
  if (smsCountdown) {
    clearInterval(smsCountdown)
    smsCountdown = null
    smsButtonDisabled.value = false
    smsButtonText.value = '获取验证码'
  }
  // 清理表单数据（通过visible的监听会自动触发清理）
}

// 处理手机号输入
const handlePhoneInput = (value, formType) => {
  const targetForm = formType === 'sms' ? smsForm : passwordForm
  targetForm.phone = value

  // 移除非数字字符（仅对手机号格式）
  if (value && REGEX_PHONE.test(value.substring(0, 2))) {
    const numericValue = value.replace(/\D/g, '')
    targetForm.phone = numericValue
  }
}

// 防抖函数 - 避免频繁点击获取验证码
let lastSmsRequestTime = 0
const SMS_REQUEST_INTERVAL = 1000 // 1秒内防止重复提交

// 获取验证码
const handleGetSmsCode = async () => {
  // 防抖检查
  const now = Date.now()
  if (now - lastSmsRequestTime < SMS_REQUEST_INTERVAL) {
    return
  }
  lastSmsRequestTime = now

  // 验证手机号
  if (!smsForm.phone) {
    ElMessage.error('请输入手机号')
    return
  }

  const phoneValid = REGEX_PHONE.test(smsForm.phone)
  if (!phoneValid) {
    ElMessage.error('手机号格式不正确')
    return
  }

  // 模拟发送验证码
  smsButtonDisabled.value = true
  let countdown = 60
  smsButtonText.value = `${countdown}秒后重新获取`

  if (smsCountdown) {
    clearInterval(smsCountdown)
  }

  smsCountdown = setInterval(() => {
    countdown--
    smsButtonText.value = `${countdown}秒后重新获取`
    if (countdown <= 0) {
      clearInterval(smsCountdown)
      smsButtonDisabled.value = false
      smsButtonText.value = '获取验证码'
    }
  }, 1000)

  // API请求
  try {
    const res = await domesticUserCenter.sendSms({
      phone: smsForm.phone
    })
    console.log('sendSms', res)
    if (res.code == 200) {
      ElMessage.success('验证码发送成功')
    } else {
      ElMessage.error(res.msg || '验证码发送失败')
      // 发送失败时重置按钮状态
      clearInterval(smsCountdown)
      smsButtonDisabled.value = false
      smsButtonText.value = '获取验证码'
    }
  } catch (err) {
    console.error('发送验证码失败:', err)
    ElMessage.error('验证码发送失败，请稍后重试')
    // 发生错误时重置按钮状态
    clearInterval(smsCountdown)
    smsButtonDisabled.value = false
    smsButtonText.value = '获取验证码'
  }
}

// 验证码登录
const handleSmsLogin = async () => {
  if (!smsFormRef.value) return
  if (!agreementChecked.value) {
    ElMessage({
      type: 'error',
      customClass: 'custom-error-message-icon',
      dangerouslyUseHTMLString: true,
      message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">请阅读并同意用户协议`,
      offset: 65
    })
    return
  }

  // 验证表单
  if (!smsFormValid.value) {
    ElMessage.error('请填写正确的手机号和验证码')
    return
  }

  try {
    loading.value = true

    // 模拟登录请求
    const loginRes = await domesticUserCenter.createLogin()

    // 手机号+验证码登录
    const res = await loginRes.phone({
      phone: smsForm.phone,
      auth: smsForm.smsCode,
    })

    console.log('验证码登录结果', res)
    if (res.code == 200) {
      const userData = {
        userInfo: res.data,
        token: res.data.token,
        sign: res.data.sign,
        uid: res.data.uid,
      }

      userStore.login(userData)
      emit('loginSuccess', userData)
      hideLoginDialog()
    } else {
      ElMessage.error(res.msg || '登录失败')
    }
  } catch (err) {
    console.error('登录失败:', err)
    ElMessage.error(err.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 密码登录
const handlePasswordLogin = async () => {
  if (!passwordFormRef.value) return
  if (!agreementChecked.value) {
    // ElMessage.error('请阅读并同意用户协议')
    ElMessage({
      type: 'error',
      customClass: 'custom-error-message-icon',
      dangerouslyUseHTMLString: true,
      message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">请阅读并同意用户协议`,
      offset: 65
    })
    return
  }

  // 验证表单
  // if (!passwordFormValid.value) {
  //   ElMessage.error('请填写正确的登录信息')
  //   return
  // }

  try {
    loading.value = true

    // 模拟登录请求
    const loginRes = await domesticUserCenter.createLogin()

    // 账号密码登录
    const res = await loginRes.userNameWithPwd({
      loginMode: "USERNAME",
      userName: passwordForm.phone,
      auth: passwordForm.password,
    })

    console.log('账号密码登录', res)
    if (res.code == 200) {
      const userData = {
        userInfo: res.data,
        token: res.data.token,
        sign: res.data.sign,
        uid: res.data.uid,
      }

      userStore.login(userData)
      emit('loginSuccess', userData)

      // 如果用户勾选了记住密码，保存到localStorage
      if (passwordForm.rememberMe) {
        // 使用简单的Base64编码存储（注意：这只是基础防护，实际应用可能需要更安全的加密方式）
        const encodedPhone = btoa(encodeURIComponent(passwordForm.phone))
        const encodedPassword = btoa(encodeURIComponent(passwordForm.password))
        localStorage.setItem('rememberedAccount', encodedPhone)
        localStorage.setItem('rememberedPassword', encodedPassword)
      } else {
        // 如果未勾选，清除可能存在的保存信息
        localStorage.removeItem('rememberedAccount')
        localStorage.removeItem('rememberedPassword')
      }

      hideLoginDialog()
    } else {
      ElMessage({
        type: 'error',
        customClass: 'custom-error-message-icon',
        dangerouslyUseHTMLString: true,
        message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">${res.msg || '登录失败'}`,
        offset: 65
      })
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage({
      type: 'error',
      customClass: 'custom-error-message-icon',
      dangerouslyUseHTMLString: true,
      message: `<img src="${errorIcon}" alt="success-icon" style="width: 20px; height: 20px; margin-right: 4px;">${error.message || '登录失败，请稍后重试'}`,
      offset: 65
    })
  } finally {
    loading.value = false
  }
}

// 忘记密码
const handleForgotPassword = () => {
  innerVisible.value = true
}

// 协议点击处理
const handleAgreementClick = (type) => {
  if (type === 'user') { // 用户协议
    var url = 'https://www.ldyuncs.com/ldy/pcpolicy/purchase_policy.html';
  } else if (type === 'privacy') { // 隐私政策
    var url = 'https://www.ldyuncs.com/ldy/pcpolicy/private_policy.html';
  } else if (type === 'platform') { // 平台免责声明
    var url = 'https://www.ldyuncs.com/ldy/pcpolicy/user_policy.html';
  }
  // 发送消息给C#后端
  window.chrome.webview.postMessage({
    action: 'openExternalBrowser',
    url: url
  });
}

// 暴露方法给父组件
defineExpose({
  showLoginDialog,
  hideLoginDialog
})

// 弹窗打开时的处理
const handleOpen = async () => {
  try {
    const loginRes = await domesticUserCenter.createLogin()
    console.log("获取登录方式成功", loginRes);

    // 从localStorage读取保存的账号密码并填充到表单
    const encodedPhone = localStorage.getItem('rememberedAccount')
    const encodedPassword = localStorage.getItem('rememberedPassword')

    if (encodedPhone && encodedPassword) {
      try {
        // 解码并填充表单
        const phone = decodeURIComponent(atob(encodedPhone))
        const password = decodeURIComponent(atob(encodedPassword))

        passwordForm.phone = phone
        passwordForm.password = password
        passwordForm.rememberMe = true

        // 切换到密码登录选项卡
        activeTab.value = 'password'
      } catch (decodeError) {
        console.error('解码保存的账号密码失败:', decodeError)
        // 解码失败时清除可能损坏的数据
        localStorage.removeItem('rememberedAccount')
        localStorage.removeItem('rememberedPassword')
      }
    }
  } catch (error) {
    console.error("获取登录方式失败:", error)
  }
}


</script>

<style lang="scss" scoped>
.login-dialog-content {
  height: 531px;
  display: flex;
  box-sizing: border-box;

  .scan-login-section {
    background: linear-gradient(90deg, #141414 54.07%, #252525 100%);

    .sub-scan-login-section {
      width: 334px;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: url('@/assets/images/login/login-left-bg.png') no-repeat;
      background-position: left bottom;
      background-size: 100% 40%;

      .scan-qr-code {
        width: 136px;
        height: 136px;
        border-radius: 4px;
        overflow: hidden;

        .qr-code-img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }

      .scan-login-text {
        width: 136px;
        margin-top: 20px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        color: #888;
        border: 1px solid #2a2a26;

        .text-img {
          display: block;
          margin-right: 2px;
        }
      }
    }

  }

  .account-login-section {
    background: #141414;
    width: 100%;

    .sub-account-login-section {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-sizing: border-box;
      background: url('@/assets/images/login/login-right-bg.png') no-repeat;
      background-position: center top;
      background-size: 100% 60%;

      .login-tabs {
        width: 332px;
        margin-top: 92px;
        margin-bottom: 10px;

        :deep(.el-tabs__nav-wrap:after) {
          background-color: transparent !important;
        }

        :deep(.el-tabs__nav) {
          width: 100% !important;
        }

        :deep(.el-tabs__item) {
          width: 50%;
          color: #e2e2e2;
          font-size: 18px;
          padding: 0 !important;
        }

        :deep(.el-tabs__item.is-active) {
          color: #fff !important;
          font-weight: bold;
        }

        :deep(.el-tabs__active-bar) {
          background-color: transparent;
        }
      }

      .login-form {
        width: 332px;
        flex: 1;

        :deep(.el-input__wrapper) {
          background: transparent !important;
          border-color: #47494A;
        }

        .el-input__suffix {
          color: #999 !important;
        }

        .sms-code-input {}

        :deep(.el-input-group__append) {
          background-color: transparent !important;
          border: none !important;
          color: #ffe500 !important;
          box-shadow: none !important;
          padding: 0 !important;
          // box-shadow: 0 1px 0 0 var(--el-input-border-color) inset, 0 -1px 0 0 var(--el-input-border-color) inset, -1px 0 0 0 var(--el-input-border-color) inset;
        }

        .get-sms-button {
          padding: 0 10px;
          position: absolute;
          right: 20px;
          // height: 100%;
          // width: 100px;
          // background: transparent !important;
          // border: none !important;
          // color: #ffe500 !important;
          // box-shadow: none !important;
          // padding: 0 !important;
        }

        .login-submit-button {
          width: 100%;
          height: 48px;
          background: #666 !important;
          border-color: #666 !important;
          color: #999 !important;
          font-weight: bold;
          padding: 12px 0;
          cursor: not-allowed;
          border-radius: 4px;
        }

        .login-submit-button-active {
          background: #ffe500 !important;
          border-color: #ffe500 !important;
          color: #121212 !important;
          cursor: pointer;
        }

        .login-submit-button:hover {
          background: #ffe500 !important;
          border-color: #ffe500 !important;
          color: #121212 !important;
        }

        .forgot-password {
          display: flex;
          color: #888 !important;
          justify-content: center;
        }

        .form-actions {
          :deep(.el-form-item__content) {
            display: flex;
            justify-content: space-between !important;
            align-items: center;
          }

          // margin-bottom: 20px;
          // background: red;

          .remember-me {
            color: #888 !important;
          }

          // 输入框选中状态样式
          .el-input__wrapper.is-focused {
            box-shadow: 0 0 0 1px #ff9d00 !important;
            border-color: #ff9d00 !important;
          }

          // 输入框错误状态样式
          .el-form-item.is-error .el-input__wrapper {
            border-color: #ff4949 !important;
          }

          // 自动登录选项样式
          .auto-login {
            // margin-left: 20px;
          }
        }

        // 密码可见性切换图标样式
        .password-toggle-icon {
          color: #999;
          cursor: pointer;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 20px;
          height: 20px;

          &:hover {
            color: #ff9d00;
          }
        }
      }

      .agreement-section {
        font-size: 12px;
        margin-bottom: 30px;

        .agreement-checkbox {
          color: #999 !important;

          .el-checkbox__label {
            color: #999 !important;
          }
        }

        :deep(.el-link__inner) {
          color: #4CE0EB;
        }
      }
    }
  }
}
</style>